﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;

namespace AppManagement.BusManagers
{
    #region Using
    using AppManagement.Models;
    using AppManagement.Repositories;
    using AppManagement.Helpers;
    #endregion

    /// <summary>
    ///  insert new khenthuong progress
    /// </summary>
    public partial class FrmCapNhatDVSuDung : DevComponents.DotNetBar.Office2007Form
    {
        public EventHandler Handler { get; set; }
        // Hidden files are used to store ids 
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaDV;
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaBS;
        private EnumUpdateMode UpdateMode = EnumUpdateMode.INSERT;
        private int MaPKDV;

        public FrmCapNhatDVSuDung(string madichvu = "", string mabacsi = "", int mapkdv = 0)
        {
            InitializeComponent();
            InitHiddenFields();

            if (madichvu != "" && mabacsi != "" && mapkdv != 0)
            {
                txtMaDV.Text = madichvu;
                txtDV.Text = DichVuRepository.SelectByID(madichvu).TenDV;
                txtMaBS.Text = mabacsi;
                txtBS.Text = BacSi_NhanVienRepository.SelectByID(mabacsi).ToString();
                MaPKDV = mapkdv;
                InitUpdateMode(true);

                var pkdv = PhieuKham_DichVuRepository.SelectByID(mapkdv);
                txtKetLuan.Text = pkdv.KetLuanDV;
                txtGhiChu.Text = pkdv.GhiChu;

                UpdateMode = EnumUpdateMode.UPDATE;
                LoadDSChiSo();
            }
            else
            {
                InitUpdateMode(false);
                UpdateMode = EnumUpdateMode.INSERT;
            }
        }

        public void InitUpdateMode(bool val)
        {
            btnCapNhat.Enabled = val;
            txtKetLuan.ReadOnly = !val;
            txtGhiChu.ReadOnly = !val;
            btnChonDV.Enabled = !val;
            btnChonBS.Enabled = !val;
        }

        /// <summary>
        /// Load danh sach cac chi so ung voi dich vu
        /// </summary>
        public void LoadDSChiSo()
        {
            var lstItem = ChiSo_DichVuRepository.SelectByMaDV(txtMaDV.Text);
            var lstchiso_pkdv = ChiSo_PhieuKhamDVRepository.SelectByMaPKDV(MaPKDV);

            lstvDanhSachDV.Items.Clear();
            
            for (int i = 0; i < lstItem.Count; i++)
            {
                var objListViewItem = new ListViewItem();
                objListViewItem.Text = lstItem[i].MaCS;
                objListViewItem.SubItems.Add(lstItem[i].ChiSo.TenCS);
                objListViewItem.SubItems.Add(lstItem[i].GiaTri);//gia tri chuan
                objListViewItem.SubItems.Add("");
                for (int j = 0; j < lstchiso_pkdv.Count; j++)
                {
                    if (lstchiso_pkdv[j].MaCS == lstItem[i].MaCS)
                    {
                        objListViewItem.SubItems[3].Text = lstchiso_pkdv[j].GiaTri;//gia tri xet nghiem
                        break;
                    }
                }
                lstvDanhSachDV.Items.Add(objListViewItem);
            }
        }

        /// <summary>
        /// Init hidden fields
        /// </summary>
        public void InitHiddenFields()
        {
            // Add a new textbox
            txtMaDV = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaDV",
                Text = ""
            };
            txtMaDV.Visible = false;

            // Add a new textbox
            txtMaBS = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaBS",
                Text = ""
            };
            txtMaBS.Visible = false;
        }

        private void btnChonDV_Click(object sender, EventArgs e)
        {
            FrmChonDV frm = new FrmChonDV();
            frm.Handler += GetDV;
            frm.ShowDialog();
        }

        public void GetDV(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            txtMaDV.Text = comp[0];
            txtDV.Text = comp[1];
        }

        /// <summary>
        /// Validate user input
        /// </summary>
        /// <param name="isUpdate"></param>
        /// <returns></returns>
        private bool ValidateInput(ref string errorText)
        {
            if (txtMaDV.Text == "")
            {
                errorText = "Vui lòng chọn dịch vụ";
                return false;
            }
            if (txtMaBS.Text == "")
            {
                errorText = "Vui lòng chọn bác sĩ";
                return false;
            }
            return true;
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            var errorText = "";

            if (UpdateMode == EnumUpdateMode.INSERT)
            {
                if (!ValidateInput(ref errorText))
                {
                    MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                TransferDataInfo(this, new TransferSimpleDataEvent(txtMaDV.Text + "#" + txtMaBS.Text));
            }
            else
            {
                if (ActionUpdate())
                {
                    MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    TransferDataInfo(this, new TransferSimpleDataEvent(txtKetLuan.Text + "#" + txtGhiChu.Text));
                }
                else
                {
                    MessageBox.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        public bool ActionUpdate()
        {
            // Open connection
            DataContext.Instance.Connection.Open();
            // Define a transaction for the operations
            using (var transaction = DataContext.Instance.Connection.BeginTransaction())
            {
                var pkdv = PhieuKham_DichVuRepository.SelectByID(MaPKDV);
                pkdv.KetLuanDV = txtKetLuan.Text;
                pkdv.GhiChu = txtGhiChu.Text;

                if (PhieuKham_DichVuRepository.Save())
                {
                    var lstchiso_pkdv = ChiSo_PhieuKhamDVRepository.SelectByMaPKDV(MaPKDV);
                    for (int i = 0; i < lstchiso_pkdv.Count; i++)
                    {
                        if (!ChiSo_PhieuKhamDVRepository.Delete(lstchiso_pkdv[i].MaCSPKDV))
                        {
                            return false;
                        }
                    }

                    for (int i = 0; i < lstvDanhSachDV.Items.Count; i++)
                    {
                        var chiso_pkdv = new ChiSo_PhieuKhamDV
                        {
                            MaPKDV = this.MaPKDV,
                            MaCS = lstvDanhSachDV.Items[i].Text,
                            GiaTri = lstvDanhSachDV.Items[i].SubItems[3].Text
                        };
                        if (!ChiSo_PhieuKhamDVRepository.Insert(chiso_pkdv))
                        {
                            return false;
                        }
                    }
                }

                // Mark the transaction as complete
                transaction.Commit();
                DataContext.Instance.Connection.Close();
            }

            return true;
        }

        /// <summary>
        ///  function is used to transfer data when event would be raised
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransferDataInfo(object sender, TransferSimpleDataEvent e)
        {
            this.Close();
            this.Handler(this, e);
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnChonBS_Click(object sender, EventArgs e)
        {
            FrmQuanLyNhanVien frm = new FrmQuanLyNhanVien(true);
            frm.Handler += GetBS;
            frm.ShowDialog();
        }

        public void GetBS(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            txtMaBS.Text = comp[0];
            txtBS.Text = comp[1];
        }

        private void FrmCapNhatDVSuDung_Load(object sender, EventArgs e)
        {

        }

        private void btnCapNhatGiaTriChiSo_Click(object sender, EventArgs e)
        {
            if (lstvDanhSachDV.SelectedItems.Count > 0)
            {
                FrmCapNhatChiSoDichVu frm = new FrmCapNhatChiSoDichVu(lstvDanhSachDV.SelectedItems[0].SubItems[3].Text);
                frm.Handler += CapNhatChiSoDichVu;
                frm.ShowDialog();
            }
        }

        public void CapNhatChiSoDichVu(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            lstvDanhSachDV.SelectedItems[0].SubItems[3].Text = comp[0];
        }

        private void lstvDanhSachDV_DoubleClick(object sender, EventArgs e)
        {
            if (lstvDanhSachDV.SelectedItems.Count > 0)
            {
                FrmCapNhatChiSoDichVu frm = new FrmCapNhatChiSoDichVu(lstvDanhSachDV.SelectedItems[0].SubItems[3].Text);
                frm.Handler += CapNhatChiSoDichVu;
                frm.ShowDialog();
            }
        }
    }
}